#include <huniplacer_3d/LogPanel.h>

#include <GL/gl.h>
#include <GL/freeglut.h>

#include <huniplacer_3d/PanelPart.h>

#include <string>
#include <vector>

#include <iostream>
#include <stdio.h>
#include <string.h>

LogPanel::LogPanel(unsigned int x, unsigned int y, unsigned int width, unsigned int height, float r, float g, float b, float bg_r, float bg_g, float bg_b, char* value_type, char* name) :
				PanelPart(name, x, y, width, height, r, g, b, bg_r, bg_g, bg_b, value_type) {
	text_height = 16;
	text_width = 16; //TODO: don't do this hardcoded
}

void LogPanel::write(std::string data) {
	data = "*" + data;
	
	while (data.size() * text_width > width - text_width) {
		log.push_back(data.substr(0, width/text_width - 1));
		
		data = " " + data.substr(width/text_width - 1, data.size() - width/text_width + 1);
	}
	
	log.push_back(data);
}

void LogPanel::draw() {
	int screen_height = glutGet(GLUT_SCREEN_HEIGHT);
	
	//Background
	set_color3f(bg_color_r, bg_color_g, bg_color_b);
	glBegin(GL_QUADS);
		glVertex2i(x, screen_height - y - height);
		glVertex2i(x + width, screen_height - y - height); 
		glVertex2i(x + width, screen_height - y);
		glVertex2i(x, screen_height - y);
	glEnd();
	
	//Display name
	set_color3f(color_r, color_g, color_b);
	translate_text(x, screen_height - height - y - 2);
   
   char* n = new char[name.size()]; 
   strcpy(n, name.c_str());
   draw_string(n);
   
   //Write log
   for (unsigned int i = 0; i < log.size(); i++) {
   	unsigned int text_y = screen_height - y - i*text_height;
   	if (text_y >= screen_height - y - height + text_height) {
			translate_text(x, text_y);
   		draw_string((char*)log[log.size() - 1 - i].c_str());
   	}
   }
}
